<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个人资料</title>
</head>

<body>
    <h1>个人资料</h1>
    <ul>
        <li>
            姓名 <input type="text" placeholder="请输入姓名" id="name">
        </li>
        <li>
            年龄 <input type="text" placeholder="请输入年龄" id="age">
        </li>
        <li>
            头像
            <img src="" alt="" width="100" height="100" id="avatar">
            <input type="file" id="upload">
        </li>
        <li>
            <button id="submit">修改</button>
        </li>
    </ul>
    <script src="/javascripts/jquery.min.js"></script>
    <script>
        $.ajax({
            url: "/profile/select/1",
            success: (res) => {
                let data = res.data;
                $('#name').val(data.name);
                $('#age').val(data.age);
                $('#avatar').attr('src', data.avatar);
            }
        })
        $('#upload').change(function () {
            let file = this.files[0];
            //FileReader
            let fr = new FileReader();
            fr.readAsDataURL(file);
            fr.onload = () => {
                $('#avatar').attr('src', fr.result);
            }
        });
        $('#submit').click(() => {
            let file = $('#upload')[0].files[0];
            let fd = new FormData();
            fd.append('avatar', file);
            //jquery
            $.ajax({
                url:"/upload",
                method:"post",
                data:fd,
                contentType:false,
                processData:false,
                success:(res)=>{
                    $('#avatar').attr('src',res.url);
                    $.ajax({
                        url:"/profile/update/1",
                        data:{
                            name:$('#name').val(),
                            age:$('#age').val(),
                            avatar:res.url,
                        },
                        method:"put",
                        success:(res)=>{
                            if(res.code==200){
                                alert(res.msg);
                            }else{
                                alert(res.msg);
                            }
                        }
                    })
                }
            })
            //fetch
            // fetch('/upload', {
            //     method: "post",
            //     data: fd,
            //     headers: {
            //         "Content-Type": "multipart/form-data"
            //     }
            // }).then(res => res.json())
            //     .then(res => {
            //         console.log(res);
            //     })
        })
    </script>
</body>

</html>